package com.open4cn.simulator.config.server.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.open4cn.simulator.config.entity.DeviceStatusEntity;
import com.open4cn.simulator.config.mapper.DeviceStatusMapper;
import com.open4cn.simulator.config.server.IDeviceStatusServer;
import com.open4cn.simulator.core.device.DeviceStatusDO;
import com.open4cn.simulator.core.device.IDeviceStatusRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description
 * @Email yinxiaopeng@zj.tech
 * @date 2022-05-15 02:21
 */
@Service
public class DeviceStatusServerImpl implements IDeviceStatusServer, IDeviceStatusRepository {

    @Autowired
    private DeviceStatusMapper deviceStatusMapper;

    @Override
    public boolean save(DeviceStatusDO deviceStatusDO) {
        DeviceStatusEntity deviceStatusEntity = new DeviceStatusEntity();
        deviceStatusEntity.setDeviceId(deviceStatusDO.getDeviceId());
        deviceStatusEntity.setBrand(deviceStatusDO.getBrand());
        deviceStatusEntity.setModel(deviceStatusDO.getModel());
        deviceStatusEntity.setStatusJson(deviceStatusDO.getStatusJson());
        deviceStatusEntity.setUpdateTime(LocalDateTime.now());

        if (exists(deviceStatusDO.getDeviceId())) {
            deviceStatusEntity.setId(getByDeviceId(deviceStatusDO.getDeviceId()).getId());
            return deviceStatusMapper.updateById(deviceStatusEntity) > 0;
        } else {
            deviceStatusEntity.setEnable(1);
            deviceStatusEntity.setCreateTime(LocalDateTime.now());
            return deviceStatusMapper.insert(deviceStatusEntity) > 0;
        }
    }

    @Override
    public DeviceStatusDO get(String deviceId) {
        DeviceStatusEntity entity = getByDeviceId(deviceId);
        if (null == entity) {
            return null;
        }

        DeviceStatusDO deviceStatusDO = new DeviceStatusDO();
        deviceStatusDO.setDeviceId(entity.getDeviceId());
        deviceStatusDO.setBrand(entity.getBrand());
        deviceStatusDO.setModel(entity.getModel());
        deviceStatusDO.setStatusJson(entity.getStatusJson());
        return deviceStatusDO;
    }

    @Override
    public DeviceStatusEntity getByDeviceId(String deviceId) {
        if (CharSequenceUtil.isEmpty(deviceId)) {
            return null;
        }
        LambdaQueryWrapper<DeviceStatusEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DeviceStatusEntity::getDeviceId, deviceId);
        queryWrapper.eq(DeviceStatusEntity::getEnable, 1);
        return deviceStatusMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean exists(String deviceId) {
        return null != getByDeviceId(deviceId);
    }
}
